package com.shxy.service.impl;

import com.shxy.dao.StaffDao;
import com.shxy.entity.Staff;
import com.shxy.service.IStaffService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 员工信息管理实现类
 */
@Service
public class StaffService implements IStaffService {
    @Autowired
    private StaffDao staffDao;

    @Override
    public List<Staff> findAll() {
        return staffDao.findAll();
    }

    @Override
    public Page<Staff> list(int page, int size) {
        Page<Staff> pagedList = staffDao.findAll(PageRequest.of(page - 1, size));
        return pagedList;
    }

    @Override
    public Page<Staff> list(String name, String sex, int page, int size) {
        Specification<Staff> staffSpecification = (root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            if(StringUtils.isNoneBlank(name)) {
                Path<String> namePath = root.get("name");
                Predicate nameLike = criteriaBuilder.like(namePath, "%" + name + "%");
                list.add(nameLike);
            }

            if(StringUtils.isNoneBlank(sex)) {
                Path<Object> sexPath = root.get("sex");
                Predicate sexEqual = criteriaBuilder.equal(sexPath, sex);
                list.add(sexEqual);
            }

            Predicate[] predicates = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(predicates));
        };
        return staffDao.findAll(staffSpecification, PageRequest.of(page - 1, size));
    }

    @Override
    public boolean exists(Staff staff) {
        // 1、根据身份证获取用户信息
        Staff s = staffDao.findByIdCard(staff.getIdCard());
        // 2、如果该身份证存在，且与查询用户不同，则返回真
        return s != null && s.getId() != staff.getId();
    }

    @Override
    public void addNew(Staff staff) {
        save(staff);
    }

    @Override
    public void update(Staff staff) {
        save(staff);
    }

    @Override
    public boolean exists(int id) {
        return staffDao.findById(id).isPresent();
    }

    @Override
    public void deleteById(int id) {
        staffDao.deleteById(id);
    }

    private void save(Staff staff) {
        String idCard = staff.getIdCard();
        if(StringUtils.isNoneBlank(idCard)) {
            staff.setBirthday(String.format("%s-%s-%s", idCard.substring(5, 8), idCard.substring(9, 10), idCard.substring(11, 12)));
        }
        staffDao.save(staff);
    }
}
